package org.example.controller;

import com.auth0.jwt.JWT;
import jakarta.validation.constraints.Pattern;
import org.example.pojo.Result;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.utils.JwtUtil;
import org.example.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    static {
        System.out.println("进入user接口");
    }
    @Autowired
    private UserService userService;

    @PostMapping("/hello")
    public String hello(){
        return "你好";
    }

    //    用户注册
    @PostMapping("/register")
    public Result regist(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = userService.findByName(username);
        if (user != null) { //  用户名已经存在了
            return Result.error("用户名已经存在了");
        } else { //  用户名不存在
            userService.register(username, password);
            return Result.success();
        }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
//        根据用户名查询用户
        User loginUser = userService.findByName(username);
//        判断该用户是否存在
        if (loginUser == null) {
            return Result.error("用户名错误");
        }
//        判断密码是否正确  loginUser中的密码是密文的
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
//            登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",username);
            claims.put("name",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }
}
